package com.atguigu.gmall.realtime.dwd.db.app;

import com.atguigu.gmall.realtime.common.base.BaseSQLApp;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.SQLUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @author Felix
 * @date 2024/7/29
 * 评论事实表
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、DwdInteractionCommentInfo
 */
public class DwdInteractionCommentInfo extends BaseSQLApp {
    public static void main(String[] args) {
        new DwdInteractionCommentInfo().start(10012,4,Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, StreamTableEnvironment tableEnv) {
        //TODO 从kafka的topic_db主题中读取数据创建动态表---kafka连接器
        readOdsDb(tableEnv, "dwd_interaction_comment_info");

        //tableEnv.executeSql("select * from topic_db").print();

        //TODO 过滤出评论数据  table='comment_info' type='insert'
        Table commentInfo = tableEnv.sqlQuery("select \n" +
                "    `data`['id'] id,\n" +
                "    `data`['user_id'] user_id,\n" +
                "    `data`['sku_id'] sku_id,\n" +
                "    `data`['appraise'] appraise,\n" +
                "    `data`['comment_txt'] comment_txt,\n" +
                "    ts,\n" +
                "    pt\n" +
                "from topic_db where `table`='comment_info' and `type`='insert'");
        tableEnv.createTemporaryView("comment_info",commentInfo);

        //tableEnv.executeSql("select * from comment_info").print();

        //TODO 从HBase中读取字典表数据创建动态表---hbase连接器
        readBaseDic(tableEnv);

        //tableEnv.executeSql("select dic_code,dic_name from base_dic").print();
        //TODO 关联评论和字典数据---lookup join
        Table joinedTable = tableEnv.sqlQuery("SELECT \n" +
                "    id,user_id,sku_id,appraise,dic.dic_name as appraise_name,comment_txt,ts \n" +
                "FROM comment_info AS c\n" +
                "  JOIN base_dic FOR SYSTEM_TIME AS OF c.pt AS dic\n" +
                "    ON c.appraise=dic.dic_code");
        //joinedTable.execute().print();

        //TODO 将关联的结果写到kafka主题中---upsert-kafka连接器
        //7.1 创建动态表和要写入的kafka主题进行映射
        tableEnv.executeSql("CREATE TABLE "+Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO+" (\n" +
                "  id string,\n" +
                "  user_id string,\n" +
                "  sku_id string,\n" +
                "  appraise string,\n" +
                "  appraise_name string,\n" +
                "  comment_txt string,\n" +
                "  ts bigint,\n" +
                "  PRIMARY KEY (id) NOT ENFORCED\n" +
                ") " + SQLUtil.getUpsertKafkaDDL(Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO));
        //7.2 写入
        joinedTable.executeInsert(Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO);
    }

}
